package com.congee02.ticket;

/**
 * @author congee02
 * @date 1/31/2023 7:38 PM
 */
public class SellTicketRunnableImplTest {

    public static void main(String[] args) {
        ThreadProvider provider = new SellTicketRunnableImpl();
        Thread[] threads = new Thread[3];
        for (int i = 0 ; i < threads.length ; i ++ ) {
            threads[i] = provider.thread();
        }
        for (int i = 0 ; i < threads.length ; i ++ ) {
            threads[i].start();
        }
    }

    private static class SellTicketRunnableImpl implements Runnable, ThreadProvider {

        private int ticketNum = 100;

        @Override
        public void run() {
            while (ticketNum > 0) {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " 售出一张票，剩余票数: " + -- ticketNum);
            }
        }
    }

    /**
     * 允许 获取 Runnable 被 Thread 包装的对象
     */
    private interface ThreadProvider {
        /**
         * 获取 Runnable 被 Thread 包装的对象
         *
         * @return Runnable 被 Thread 包装的对象
         */
        default Thread thread() {
            if (this instanceof Runnable) {
                return new Thread((Runnable) this);
            }
            return null;
        }
    }
    
}
